﻿/// <reference path="app.js" />
/// <reference path="api.js" />
//==========================处理Cookie===============================
/*
包含模块:

1.Cookie操作(getCookie(cookie名称),setCookie(cookie名称,cookies值,过期时间));

2.打开子窗体函数(openChild(Url,title,高,宽))

3.设置body高度等于窗体高度SetWinHeight(元素)

4.Form表单提交,input标签加上required="required"时可检查是否为空 FormSubmit(url, data, "Add 或者 Edit", func执行成功后的额外方法);

5.格式化Datagrid Date日期函数

6.获取URL参数

7.获取CommType表的值列表

8.将json【】数组转换为json-tree【】数组，转换后对象每个会增加一个自定义字符串的children数组字段
*/
//=============================Cookie操作========================================
//读取cookie
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
//写入cookie
function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name +
        "=" +
        escape(value) +
        ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString()) + ";path = /";
};
//==========================设置元素高度===================================
function SetWinHeight(e) {
    var height = window.innerHeight;
    e.css('height', height + 'px');
}
//==========================Form表单提交========================================
function FormSubmit(url, data, type, func) {
    var isError = false;

    //验证combo控件
    $("input.easyui-combobox, input.easyui-combotree").each(function (d, i) {
        if ($(this).is(':required')) {
            if ($(this).combo("getValue") === "" && isError === false) {
                isError = true;
               // Showbo.Msg.alert(messageToI18n($(this).attr('id')) + " " + messageToI18n("CanNotBeNull"));
                api.alert({
                    title: messageToI18n("SystemPrompt"),
                    msg: messageToI18n($(this).attr('id')) + " " + messageToI18n("CanNotBeNull")
                });
            }
        }
    });

    //验证一般Input控件
    $("input.dfinput").each(function (d, i) {
        if ($(this).is(':required') && !($(this).hasClass("easyui-combobox")) && !($(this).hasClass("easyui-combotree"))) {
            if ($(this).val() === "" && isError === false) {
                isError = true;
                //Showbo.Msg.alert(messageToI18n($(this).attr('id')) + " " + messageToI18n("CanNotBeNull"));
                api.alert({
                    title: messageToI18n("SystemPrompt"),
                    msg: messageToI18n($(this).attr('id')) + " " + messageToI18n("CanNotBeNull")
                });
            }
            else if ($(this).data('valid') && isError === false) {
                var s = eval("(" + $(this).data('valid') + ")");
                if (s.type === "number") {
                    if (!IsNumeric($(this).val())) {
                        isError = true;
                        //Showbo.Msg.alert(messageToI18n($(this).attr('id')) + " " + messageToI18n("MustBeAnInteger"));
                        api.alert({
                            title: messageToI18n("SystemPrompt"),
                            msg: messageToI18n($(this).attr('id')) + " " + messageToI18n("MustBeAnInteger")
                        });
                    }
                }
                else if (s.type === "phone") {
                    if (!IsMobile($(this).val())) {
                        isError = true;
                        // Showbo.Msg.alert(messageToI18n($(this).attr('id')) + " " + messageToI18n("MustBeForPhoneNumber"));
                        api.alert({
                            title: messageToI18n("SystemPrompt"),
                            msg: messageToI18n($(this).attr('id')) + " " + messageToI18n("MustBeForPhoneNumber")
                        });
                    }
                }
                else if (s.type === "decimal") {
                    if (!IsDecimal($(this).val())) {
                        isError = true;
                        //Showbo.Msg.alert(messageToI18n($(this).attr('id')) + " " + messageToI18n("MustBe2Bits"));
                        api.alert({
                            title: messageToI18n("SystemPrompt"),
                            msg: messageToI18n($(this).attr('id')) + " " + messageToI18n("MustBe2Bits")
                        });
                    }
                } else if (s.type === "datetime") {
                    if (!IsDate($(this).val())) {
                        isError = true;
                        //Showbo.Msg.alert(messageToI18n($(this).attr('id')) + " " + messageToI18n("MustBeADate"));
                        api.alert({
                            title: messageToI18n("SystemPrompt"),
                            msg: messageToI18n($(this).attr('id')) + " " + messageToI18n("MustBeADate")
                        });
                    }
                }
            }
        }

    });
    if (!isError) {
        url(data)
            .done(function (datas) {
                if (datas.isResult === true) {
                    if (type === "Add") {
                        // Showbo.Msg.alert(messageToI18n("AddSuccess"));
                        api.alert({
                            title: messageToI18n("SystemPrompt"),
                            msg: messageToI18n("AddSuccess"),
                        }, function (ret, err) {
                            func();
                        });
                    }
                    else if (type === "Edit") {
                        //Showbo.Msg.alert(messageToI18n("EditSuccess"));
                        api.alert({
                            title: messageToI18n("SystemPrompt"),
                            msg: messageToI18n("EditSuccess"),
                        }, function (ret, err) {
                            func();
                        });
                    }
                    else if (type === "Delete") {
                        Showbo.Msg.alert(messageToI18n("DeleteSuccess"));
                    }
                    else if (type === "operation") {
                        Showbo.Msg.alert(messageToI18n("Success"));
                    }
                    if (func !== "undefined") {
                        func();
                    }
                } else {
                    if (type === "Add") {
                        Showbo.Msg.alert(messageToI18n("AddFailed") + ":" + messageToI18n(datas.result));
                    }
                    else if (type === "Edit") {
                        Showbo.Msg.alert(messageToI18n("EditFailed") + ":" + messageToI18n(datas.result));
                    }
                    else if (type === "Delete") {
                        Showbo.Msg.alert(messageToI18n("DeleteFailed") + ":" + messageToI18n(datas.result));
                    }
                    else if (type === "operation") {
                        Showbo.Msg.alert(messageToI18n("Failed") + ":" + messageToI18n(datas.result));
                    }
                }
            });
    }
}
///===============表单验证=========
//1.判断是否是数字 
function IsNumeric(sNum) {
    var bResult = sNum.match("^(-|\\+)?\\d+(\\.\\d+)?$");
    if (bResult == null) {
        return false;
    }
    else {
        return true;
    }
}
//2.判断是否是手机号码 
function IsMobile(sMobile) {
    var bResult = sMobile.match("^[1][3|4|5|7|8]\\d{9}$");
    if (bResult == null) {
        return false;
    }
    else {
        return true;
    }
}
//3.0判断是否是货币 2位精度
function IsDecimal(sDecimal) {
    var bResult = sDecimal.match("^[0-9]*[.][0-9]{2}$");
    if (bResult == null) {
        return false;
    }
    else {
        return true;
    }
    //var bResult1 = sDecimal.match("[^0-9.-]");
    //var bResult2 = sDecimal.match("[[0-9]*[.][0-9]*[.][0-9]*");
    //var bResult3 = sDecimal.match("[[0-9]*[-][0-9]*[-][0-9]");
    //var bResult4 = sDecimal.match("(^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$)|(^([-]|[0-9])[0-9]*$)");
    //if (bResult2 != null || bResult3 != null || bResult4 == null) {
    //    return false;
    //}
    //else {
    //    return true;
    //}
}
//==================DataGrid日期处理======================
function FormatDataGridDate(value, row) {
    if (value != null) {
        return value = value.replace('T', ' ')
            .replace(/[.\n]\d+/, ' ');
    }
}

//===================获取URL参数============================
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

//=====================日期判断=============================
function IsDate(datestr) {
    var date = datestr;
    var result = date.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);

    if (result == null)
        return false;
    var d = new Date(result[1], result[3] - 1, result[4]);
    return (d.getFullYear() == result[1] && (d.getMonth() + 1) == result[3] && d.getDate() == result[4]);
}

/**
 * 获取公共的下拉列表项内容填充到Combobox
 * @param {} control :Dom对象
 * @param {} dicType :DicType
 * @param {} valueField :值字段
 * @param {} textField :显示字段
 * @returns {} none
 */
function getCommList(control, dicType, valueField, textField, onLoadSuccess) {
    $(control)
        .combobox({
            url: '' + APIUrl + 'api/Sys/CommType/GetCommTypeValue?DicType=BaseType',
            method: 'GET',
            valueField: valueField,
            textField: textField,
            panelHeight:200
        });
    if (typeof (onLoadSuccess) != 'undefined')
        $(control)
           .combobox({
               onLoadSuccess: onLoadSuccess
           });
}

//为Combox绑定数据源
//loaderFun:loader时执行的方法
//control:要绑定的控件
//textField:显示字段
//valueField:值字段
//selectFun:onSelect
function bindComobox(url,method, control, valueField, textField, selectFun,onLoadSuccess) {
    try {
        $(control)
           .combobox({
               url: url,
               method: method,
               valueField: valueField,
               textField: textField,
               editable: false,
               panelHeight: '200',
               onSelect: function (record) {
                   if (typeof (selectFun) == 'undefined') {
                       return;
                   } else {
                       selectFun(record);
                   }
               },
               onLoadSuccess: onLoadSuccess
           });
    } catch (err) {
        alert(err.message);
    }
}


function bindComoboxFromApi(control, api, valueField, textField, selectFun) {
    try {
        $(control)
           .combobox({
               loader: function (param, success) {
                   api().done(function (data) {
                       success(data);
                   });
               },
               valueField: valueField,
               textField: textField,
               onSelect: function (record) {
                   if (typeof (selectFun) == 'undefined') {
                       return;
                   } else {
                       selectFun(record);
                   }
               }
           });
    } catch (err) {
        alert(err.message);
    }
}

function bindComoboxFromApi(control, api, aipParam, valueField, textField, selectFun, bSelectFirstNode) {
    try {
        api().done(function (data) {
            bindComoboxFromData(control, data, valueField, textField, selectFun, bSelectFirstNode);
        });
    } catch (err) {
        alert(err.message);
    }
}
function bindComoboxFromApiWithParam(control, api, aipParam, valueField, textField, selectFun, bSelectFirstNode) {
    try {
        api(aipParam).done(function (data) {
            bindComoboxFromData(control, data, valueField, textField, selectFun, bSelectFirstNode);
        });
    } catch (err) {
        alert(err.message);
    }
}

function bindComoboxFromData(control, data, valueField, textField, selectFun, bSelectFirstNode) {
    try {
        $(control)
           .combobox({
               data: data,
               valueField: valueField,
               textField: textField
           });

        if (typeof (selectFun) != 'undefined' && selectFun != null)
            $(control)
               .combobox({
                   onSelect: selectFun
               });
        if (bSelectFirstNode && data && data[0] && data[0][valueField])
            $(control).combobox('select', data[0][valueField]);
    } catch (err) {
        alert(err.message);
    }
}

function comboboxSelectFirst(control) {
    var data = $(control).combobox('getData');
    var valueFieldStr = $(control).combobox('valueField');
    if (data && data[0] && data[0][valueFieldStr])
        $(control).combobox('select', data[0][valueFieldStr]);
}

function bindCombotreeFromApi(control, url, idField, pidFiled, textField, selectFun, onLoadSuccess, bSelectFirstNode, bLocal, bSync) {
    try {
        openLoading();
        api.ajax({
            url: url,
            method: 'post'
        }, function (d, err) {
            if (d) {
                console.log(JSON.stringify(d));
                bindCombotreeFromData(control, d, idField, pidFiled, textField, selectFun, onLoadSuccess, bSelectFirstNode, bLocal);
            } else {
                api.alert({ msg: JSON.stringify(d) });
            }
        });
    } catch (e) {
        alert(e.message);
    }
}

function bindCombotreeFromApiWithParam(control, url, aipParam, idField, pidFiled, textField, selectFun, bSelectFirstNode) {
    try {
        api.ajax({
            url: url,
            method: 'post',
            data: {
                values: aipParam
            }
        }, function (d, err) {
            if (d) {
                bindCombotreeFromData(control, d, idField, pidFiled, textField, selectFun, bSelectFirstNode);
            } else {
                api.alert({ msg: JSON.stringify(d) });
            }
        });
    } catch (e) {
        alert(e.message);
    }
}

function bindCombotreeFromData(control, data, idField, pidFiled, textField, selectFun, onLoadSuccess, bSelectFirstNode) {
    try {
        data = data || [];//避免data=null引起异常
        data = copyProperty(data, [idField, pidFiled, textField], ['id', 'pid', 'text'], true); //转化为easyui - tree需要的id属性
        data = toTreeData(data, "id", "pid", "children"); //转化为easyui-tree需要的json-tree格式
        //data = copyProperty(data, [  textField], [ 'text'], true); //转化为easyui - tree需要的id属性
        //data = toTreeData(data, idField, pidFiled, "children"); //转化为easyui-tree需要的json-tree格式

        $(control)
           .combotree({
               data: data
           });
        closeLoading();
        if (typeof (selectFun) != 'undefined' && selectFun != null)
            $(control)
               .combotree({
                   onSelect: selectFun
               });
        if (typeof (onLoadSuccess) != 'undefined' && onLoadSuccess != null)
            $(control)
               .combotree({
                   onLoadSuccess: onLoadSuccess
               });
        if (bSelectFirstNode && data && data[0]) {
            var firstValue = data[0][idField];
            $(control).combotree("setValue", firstValue);
        }
    } catch (err) {
        //alert(err.message);
    }
}

function combotreeSelectFirst(control) {
    var data = $(control).combotree('getData');
    if (data && data[0] && data[0]["id"])
        $(control).combotree('setValue', data[0]["id"]);
}
/**
 * 绑定区域树下拉列表
 * @param {} control             #控件ID
 * @param {} bSelectFirstNode    是否选中绑定后的第一项
 * @returns {} 
 */
function bindAreaTree(control, bSelectFirstNode, onSuccess, onSelectFun) {
    bindCombotreeFromApi(
        control, //combotree-ID
        '' + APIUrl + '/api/sys/area/GetCurrentAreas', //api
        'AreaCode', //data的ID字段
        'ParentCode',     //data的父ID字段
        'AreaName',//data中用于显示的Text字段
        onSelectFun, onSuccess, bSelectFirstNode
        );
}
/**
 * 绑定公司树下拉列表
 * @param {} control             #控件ID
 * @param {} bSelectFirstNode    是否选中绑定后的第一项
 * @returns {} 
 */
function bindCompanyTree(control, bSelectFirstNode, onSuccess, type) {
    bindCombotreeFromApi(
        control,
        //'' + APIUrl + '/api/Sys/Company/GetCompanyList?type=' + (type == undefined ? '' : type),
         '' + APIUrl + '/api/Sys/Company/GetCompanyList',
        'CompanyCode',
        'ParentCode',
        'CompanyName',
        null,
        onSuccess,
        bSelectFirstNode
        );
}



/** 
* json格式转树状结构 
* @param   {json}      json[]对象数组 
* @param   {String}    id字段的名称 
* @param   {String}    父id字段的名称 
* @param   {String}    json-tree[]对象数组，新对象中新增加的children字段的名称 
* @return  {Array}     json-tree[]对象数组 
*/
function toTreeData(jsonArray, idFieldName, pidFieldName, childrenFieldName) {
    console.log("toTreeData")
    console.log(jsonArray)
    var r = [], hash = {}, len = (jsonArray || []).length;
    for (var i = 0; i < len; i++) {
        hash[jsonArray[i][idFieldName]] = jsonArray[i];
    }
    for (var j = 0; j < len; j++) {
        var aVal = jsonArray[j], hashVP = hash[aVal[pidFieldName]];
        if (hashVP && hashVP !== aVal) {
            !hashVP[childrenFieldName] && (hashVP[childrenFieldName] = []);
            hashVP[childrenFieldName].push(aVal);
        } else {
            r.push(aVal);
        }
    }
    return r;
};

/** 
* json对象的属性复制，例如:obj.name---复制到-->obj.text
* 如果text是没有的属性，此函数会新建text属性；如果已经有text属性，bOverWrite
* @param   {object}      json对象或json对象数组
* @param   {String}    源属性的名称 
* @param   {String}    目标属性的名称 
* @param   {boolean}   json如果已有 目标属性，是否要覆盖 
* @return  {void}      无返回 
*/
function copyProperty(obj, sourcePropertyName, newPropertyName, overWrite) {
    if (obj instanceof Array || Object.prototype.toString.call(obj) === "[object Array]") {
        for (var k in obj)
            copyProperty(obj[k], sourcePropertyName, newPropertyName);
    }
    else if (typeof obj === 'object') {
        if (sourcePropertyName instanceof Array || Object.prototype.toString.call(sourcePropertyName) === "[object Array]") {
            for (var i in sourcePropertyName) {
                copyProperty(obj, sourcePropertyName[i], newPropertyName[i]);
            }
        }
        else if (typeof sourcePropertyName === 'string') {
            if ((obj[newPropertyName] && overWrite) || (!obj[newPropertyName]))
                obj[newPropertyName] = obj[sourcePropertyName];
        }
    }
    return obj;
};
/**
 * 过滤或保留某个json对象或json[]中所有对象的某些属性。
 * @param {} obj       json对象或json[]数组对象
 * @param {} props     ['prop1','prop2'..]
 * @param {} bFilter   true表示去除指定的属性['prop1','prop2'..]，false表示保留指定的属性['prop1','prop2'..]
 * @returns {}         被处理后的对象json或json[]
 */
function filterProperties(obj, props, bFilter) {
    var ret;
    if (obj instanceof Array || Object.prototype.toString.call(obj) === "[object Array]") {
        ret = [];
        for (var k in obj) {
            ret.push(filterProperties(obj[k], props, bFilter));
        }
    }
    else if (typeof obj === 'object') {
        ret = {};
        if (bFilter) {
            var map = {};
            for (var k in props)
                map[props[k]] = true;

            for (var i in obj) {
                if (!map[i]) ret[i] = obj[i];
            }
        }
        else {
            for (var i in props) {
                var arr = props[i].split(" as ");
                ret[arr[1] || arr[0]] = obj[arr[0]];
            }
        }
    }
    else {
        ret = obj;
    }
    return ret;
};
/**
 * 获取某个json对象或json[]中所有对象的prop属性的值
 * @param {} obj 
 * @param {} prop 
 * @returns {} json对象，返回一个值；json[]，返回值的数组[]
 */
function getPropertyValue(obj, prop) {
    var ret;
    if (obj instanceof Array || Object.prototype.toString.call(obj) === "[object Array]") {
        ret = [];
        for (var k in obj) {
            ret.push(obj[k][prop]);
        }
    }
    else if (typeof obj === 'object') {
        ret = obj[prop];
    }
    else {
        ret = obj;
    }
    return ret;
};
/**
 * 将值类型的数组去除冗余值
 * @param {} arr 
 * @returns {}   返回去除冗余值的数组
 */
function uniqueArray(arr) {
    var result = [], hash = {};
    for (var i = 0, elem; (elem = arr[i]) != null; i++) {
        if (!hash[elem]) {
            result.push(elem);
            hash[elem] = true;
        }
    }
    return result;
}
/**
 * 将json对象或json[]数组srcObj，的sourcePropertyName字段，复制到destObj的destPropertyName字段中。
 * 可用于集合A(主键srcIdFieldName)与集合B(主键destIdFieldName)的连接作用，连接后结果存于集合B，
 * @param {} srcObj                     
 * @param {} srcIdFieldName              
 * @param {} destObj 
 * @param {} destIdFieldName 
 * @param {} sourcePropertyName 
 * @param {} destPropertyName 
 * @param {} bOverWrite 
 * @returns {} 
 */
function copyPropertyTo(srcObj, srcIdFieldName, destObj, destIdFieldName, sourcePropertyName, destPropertyName, bOverWrite) {
    var srcArr = srcObj || [], destArr = destObj || [];
    var hashSrc = {};
    for (var k in srcArr) {
        var srcIdValue = srcArr[k][srcIdFieldName];
        if (srcIdValue !== null && srcIdValue !== "" && !hashSrc[srcIdValue])
            hashSrc[srcIdValue] = srcArr[k];
    }
    for (var k in destArr) {
        var destIdValue = destArr[k][destIdFieldName];
        if (destIdValue != null && destIdValue !== "" &&
            hashSrc[destIdValue] && typeof hashSrc[destIdValue] === 'object' && typeof destArr[k] === 'object') {
            if (sourcePropertyName instanceof Array || Object.prototype.toString.call(sourcePropertyName) === "[object Array]") {
                for (var i in sourcePropertyName) {
                    if ((destArr[k][destPropertyName[i]] && bOverWrite) || (!destArr[k][destPropertyName[i]]))
                        destArr[k][destPropertyName[i]] = hashSrc[destIdValue][sourcePropertyName[i]];
                }
            }
            else if (typeof sourcePropertyName === 'string') {
                if ((destArr[k][destPropertyName] && bOverWrite) || (!destArr[k][destPropertyName]))
                    destArr[k][destPropertyName] = hashSrc[destIdValue][sourcePropertyName];
            }
        }
    }
};
/**
 * 多语言化json对象或json[]数组中对象的多个字段的值
 * @param {} obj 
 * @param {} propertyNames 
 * @returns {} 
 */
function i18nProperties(obj, propertyNames) {
    var objArr = obj || [];
    for (var k in objArr) {
        if (propertyNames instanceof Array || Object.prototype.toString.call(propertyNames) === "[object Array]") {
            for (var i in propertyNames) {
                objArr[k][propertyNames[i]] = objArr[k][propertyNames[i]] == null ? "" : messageToI18n(objArr[k][propertyNames[i]]);
            }
        }
        else if (typeof propertyNames === 'string') {
            objArr[k][propertyNames] = objArr[k][propertyNames] == null ? "" : messageToI18n(objArr[k][propertyNames]);
        }
    }
}
/**
 * 查询objArr中，propertyNames=values的所有对象
 * @param {} objArr 
 * @param {} propertyNames 
 * @param {} value 
 * @returns {} 
 */
function searchObjByValue(objArr, propertyNames, values) {
    var ret = [];
    objArr = objArr || [];
    for (var k in objArr) {
        if (propertyNames instanceof Array || Object.prototype.toString.call(propertyNames) === "[object Array]") {
            var bEqual = true;
            for (var i in propertyNames) {
                if (!objArr[k][propertyNames[i]] || objArr[k][propertyNames[i]] !== values[i])
                    bEqual = false;
            }
            if (bEqual)
                ret.push(objArr[k]);
        }
        else if (typeof propertyNames === 'string') {
            if (objArr[k][propertyNames] && objArr[k][propertyNames] === values)
                ret.push(objArr[k]);
        }
    }
    return ret;
}

/**
 * 为Date类型添加format扩展方法
 * @param {} format 
 * @returns {} 
 */
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, // month  
        "d+": this.getDate(), // day  
        "h+": this.getHours(), // hour  
        "m+": this.getMinutes(), // minute  
        "s+": this.getSeconds(), // second  
        "S": this.getMilliseconds()
        // millisecond  
    }
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}

/**
 * 使用指定的格式化字符串对日期进行格式化
 * @param {} value  要处理的日期值
 * @param {} formatstr 格式化字符串
 * @returns {} 格式化后的日期
 */
function dateFormat(value, formatstr) {
    if (value == null || value == '') {
        return '';
    }
    var dt;
    if (value instanceof Date) {
        dt = value;
    } else {
        value = value.replace("T", " ");
        dt = new Date(value);
    }

    return dt.format(formatstr).toLocaleString();
}
var utilss = {};
utilss.vm = {};
//格式化时间
utilss.formatDate = function (value) {
    return utilss.formatDate(value, 'yyyy-MM-dd');
};

utilss.formatTime = function (value) {
    return utilss.formatDate(value, 'yyyy-MM-dd hh:mm:ss');
};
/**
* 格式化字符串
* 用法:
.formatString("{0}-{1}","a","b");
*/
utilss.formatString = function () {
    for (var i = 1; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        arguments[0] = arguments[0].replace(exp, arguments[i]);
    }
    return arguments[0];
};

/**
* 格式化时间显示方式
* 用法:format="yyyy-MM-dd hh:mm:ss";
*/
utilss.formatDate = function (v, format) {
    if (!v) return "";
    var d = v;
    if (typeof v === 'string') {
        if (v.indexOf("/Date(") > -1)
            d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
        else
            d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[0])); //.split(".")[0] 用来处理出现毫秒的情况，截取掉.xxx，否则会出错
    }
    var o = {
        "M+": d.getMonth() + 1,  //month
        "d+": d.getDate(),       //day
        "h+": d.getHours(),      //hour
        "m+": d.getMinutes(),    //minute
        "s+": d.getSeconds(),    //second
        "q+": Math.floor((d.getMonth() + 3) / 3),  //quarter
        "S": d.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

/**  
* 格式化数字显示方式   
* 用法  
* formatNumber(12345.999,'#,##0.00');  
* formatNumber(12345.999,'#,##0.##');  
* formatNumber(123,'000000');
*/
utilss.formatNumber = function (v, pattern) {
    if (v == null)
        return v;
    var strarr = v ? v.toString().split('.') : ['0'];
    var fmtarr = pattern ? pattern.split('.') : [''];
    var retstr = '';
    // 整数部分   
    var str = strarr[0];
    var fmt = fmtarr[0];
    var i = str.length - 1;
    var comma = false;
    for (var f = fmt.length - 1; f >= 0; f--) {
        switch (fmt.substr(f, 1)) {
            case '#':
                if (i >= 0) retstr = str.substr(i--, 1) + retstr;
                break;
            case '0':
                if (i >= 0) retstr = str.substr(i--, 1) + retstr;
                else retstr = '0' + retstr;
                break;
            case ',':
                comma = true;
                retstr = ',' + retstr;
                break;
        }
    }
    if (i >= 0) {
        if (comma) {
            var l = str.length;
            for (; i >= 0; i--) {
                retstr = str.substr(i, 1) + retstr;
                if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
            }
        }
        else retstr = str.substr(0, i + 1) + retstr;
    }
    retstr = retstr + '.';
    // 处理小数部分   
    str = strarr.length > 1 ? strarr[1] : '';
    fmt = fmtarr.length > 1 ? fmtarr[1] : '';
    i = 0;
    for (var f = 0; f < fmt.length; f++) {
        switch (fmt.substr(f, 1)) {
            case '#':
                if (i < str.length) retstr += str.substr(i++, 1);
                break;
            case '0':
                if (i < str.length) retstr += str.substr(i++, 1);
                else retstr += '0';
                break;
        }
    }
    return retstr.replace(/^,+/, '').replace(/\.$/, '');
};

utilss.addImg = function (storageNo, sgnInImgNo, from) {
    var length = $('ul').children('li').length;
    if (length !== 0) {
        $("ul>li")
            .each(function (i) {
                if ($(this).children('img').attr('src') === "../../Content/image/noUploadImg.jpg") {
                    $(this).remove();
                }
            });
    }
    //开始添加照片
    ++sgnInImgNo;
    //$api.setStorage(storageNo, sgnInImgNo);
    $('ul').append("<li id='li" + sgnInImgNo + "' class='aui-list-view-cell aui-img'><img onclick=imgOpt('genImg" + sgnInImgNo + "') id='showImage1" + sgnInImgNo + "' class='aui-img-object' src='../../Content/image/noUploadImg.jpg'><input id='genGps" + sgnInImgNo + "' hidden='hidden' /></li>");
    //处理图片样式
    var length = $('ul').children('li').length;
    var liCount;
    if (length === 1) {
        liCount = 12;
    } else if (length === 2) {
        liCount = 6;
    }
    else if (length === 3) {
        liCount = 4;
    }
    else if (length === 4) {
        liCount = 6;
    }
    else if (length >= 5) {
        liCount = 4;
    }
    for (var i = 1; i <= 12; i++) {
        $('ul').children('li').removeClass("aui-col-xs-" + i + "");
    }
    $('ul').children('li').addClass('aui-col-xs-' + liCount + '');
    //开始拍照有GPS信息
    //CameraPic("genImg" + sgnInImgNo + "", "genGps" + sgnInImgNo + "", "signIn", function () {
    //    $("#li" + sgnInImgNo + "").remove();
    //});
    //Camera("genImg" + sgnInImgNo + "", "genGps" + sgnInImgNo + "", from);
}


